package com.employee.servlet;

import com.employee.dao.EmployeeDao;
import com.employee.entity.Employee;
import com.employee.util.JsonResult;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 员工管理Servlet
 */
@WebServlet("/employee/*")
public class EmployeeServlet extends HttpServlet {
    
    private EmployeeDao employeeDao = new EmployeeDao();
    private Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        try {
            if ("/list".equals(pathInfo)) {
                // 分页查询
                handleList(request, out);
            } else if ("/detail".equals(pathInfo)) {
                // 查询详情
                handleDetail(request, out);
            } else if ("/generateEmpNo".equals(pathInfo)) {
                // 生成员工编号
                handleGenerateEmpNo(request, out);
            } else {
                out.print(gson.toJson(JsonResult.error("未知操作")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(JsonResult.error("系统错误：" + e.getMessage())));
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        
        String pathInfo = request.getPathInfo();
        PrintWriter out = response.getWriter();
        
        try {
            if ("/add".equals(pathInfo)) {
                // 新增
                handleAdd(request, out);
            } else if ("/update".equals(pathInfo)) {
                // 更新
                handleUpdate(request, out);
            } else if ("/delete".equals(pathInfo)) {
                // 删除
                handleDelete(request, out);
            } else if ("/deleteBatch".equals(pathInfo)) {
                // 批量删除
                handleDeleteBatch(request, out);
            } else {
                out.print(gson.toJson(JsonResult.error("未知操作")));
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(gson.toJson(JsonResult.error("系统错误：" + e.getMessage())));
        }
    }
    
    /**
     * 分页查询（支持多条件查询）
     */
    private void handleList(HttpServletRequest request, PrintWriter out) {
        String pageNumStr = request.getParameter("pageNum");
        String pageSizeStr = request.getParameter("pageSize");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String gender = request.getParameter("gender");
        String positionType = request.getParameter("positionType");
        String hireDateStartStr = request.getParameter("hireDateStart");
        String hireDateEndStr = request.getParameter("hireDateEnd");
        String salaryMinStr = request.getParameter("salaryMin");
        String salaryMaxStr = request.getParameter("salaryMax");
        
        int pageNum = 1;
        int pageSize = 10;
        Date hireDateStart = null;
        Date hireDateEnd = null;
        BigDecimal salaryMin = null;
        BigDecimal salaryMax = null;
        
        try {
            if (pageNumStr != null && !pageNumStr.isEmpty()) {
                pageNum = Integer.parseInt(pageNumStr);
            }
            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (hireDateStartStr != null && !hireDateStartStr.isEmpty()) {
                hireDateStart = sdf.parse(hireDateStartStr);
            }
            if (hireDateEndStr != null && !hireDateEndStr.isEmpty()) {
                hireDateEnd = sdf.parse(hireDateEndStr);
            }
            
            if (salaryMinStr != null && !salaryMinStr.isEmpty()) {
                salaryMin = new BigDecimal(salaryMinStr);
            }
            if (salaryMaxStr != null && !salaryMaxStr.isEmpty()) {
                salaryMax = new BigDecimal(salaryMaxStr);
            }
        } catch (NumberFormatException | ParseException e) {
            out.print(gson.toJson(JsonResult.error("参数格式错误")));
            return;
        }
        
        Map<String, Object> result = employeeDao.findByPage(pageNum, pageSize, name, phone, 
                gender, positionType, hireDateStart, hireDateEnd, salaryMin, salaryMax);
        out.print(gson.toJson(JsonResult.success("查询成功", result)));
    }
    
    /**
     * 查询详情
     */
    private void handleDetail(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        
        Employee employee = employeeDao.findById(id);
        if (employee == null) {
            out.print(gson.toJson(JsonResult.error("员工不存在")));
        } else {
            out.print(gson.toJson(JsonResult.success("查询成功", employee)));
        }
    }
    
    /**
     * 生成员工编号（用于前端预览）
     */
    private void handleGenerateEmpNo(HttpServletRequest request, PrintWriter out) {
        String positionCode = request.getParameter("positionCode");
        String hireDateStr = request.getParameter("hireDate");
        
        if (positionCode == null || positionCode.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("岗位编号不能为空")));
            return;
        }
        if (hireDateStr == null || hireDateStr.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("入职时间不能为空")));
            return;
        }
        
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date hireDate = sdf.parse(hireDateStr);
            
            String empNo = employeeDao.generateEmpNo(positionCode, hireDate);
            out.print(gson.toJson(JsonResult.success("生成成功", empNo)));
        } catch (ParseException e) {
            out.print(gson.toJson(JsonResult.error("日期格式错误")));
        }
    }
    
    /**
     * 新增员工
     */
    private void handleAdd(HttpServletRequest request, PrintWriter out) {
        String name = request.getParameter("name");
        String ageStr = request.getParameter("age");
        String gender = request.getParameter("gender");
        String phone = request.getParameter("phone");
        String hireDateStr = request.getParameter("hireDate");
        String positionType = request.getParameter("positionType");
        String positionCode = request.getParameter("positionCode");
        String salaryStr = request.getParameter("salary");
        
        // 验证必填项
        if (name == null || name.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("姓名不能为空")));
            return;
        }
        if (gender == null || gender.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("性别不能为空")));
            return;
        }
        if (phone == null || phone.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("手机号不能为空")));
            return;
        }
        
        // 验证手机号格式
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            out.print(gson.toJson(JsonResult.error("手机号格式不正确")));
            return;
        }
        
        if (positionType == null || positionType.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("岗位类型不能为空")));
            return;
        }
        if (positionCode == null || positionCode.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("岗位编号不能为空")));
            return;
        }
        
        try {
            int age = Integer.parseInt(ageStr);
            if (age < 18 || age > 100) {
                out.print(gson.toJson(JsonResult.error("年龄必须在18-100之间")));
                return;
            }
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date hireDate = sdf.parse(hireDateStr);
            
            BigDecimal salary = new BigDecimal(salaryStr);
            if (salary.compareTo(BigDecimal.ZERO) <= 0) {
                out.print(gson.toJson(JsonResult.error("薪资必须大于0")));
                return;
            }
            
            Employee employee = new Employee();
            employee.setName(name.trim());
            employee.setAge(age);
            employee.setGender(gender.trim());
            employee.setPhone(phone.trim());
            employee.setHireDate(hireDate);
            employee.setPositionType(positionType.trim());
            employee.setPositionCode(positionCode.trim());
            employee.setSalary(salary);
            
            if (employeeDao.insert(employee)) {
                out.print(gson.toJson(JsonResult.success("新增成功", employee.getEmpNo())));
            } else {
                out.print(gson.toJson(JsonResult.error("新增失败")));
            }
            
        } catch (NumberFormatException e) {
            out.print(gson.toJson(JsonResult.error("数字格式错误")));
        } catch (ParseException e) {
            out.print(gson.toJson(JsonResult.error("日期格式错误")));
        }
    }
    
    /**
     * 更新员工
     */
    private void handleUpdate(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String ageStr = request.getParameter("age");
        String gender = request.getParameter("gender");
        String phone = request.getParameter("phone");
        String hireDateStr = request.getParameter("hireDate");
        String positionType = request.getParameter("positionType");
        String positionCode = request.getParameter("positionCode");
        String salaryStr = request.getParameter("salary");
        
        // 验证必填项
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        if (name == null || name.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("姓名不能为空")));
            return;
        }
        if (gender == null || gender.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("性别不能为空")));
            return;
        }
        if (phone == null || phone.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("手机号不能为空")));
            return;
        }
        
        // 验证手机号格式
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            out.print(gson.toJson(JsonResult.error("手机号格式不正确")));
            return;
        }
        
        if (positionType == null || positionType.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("岗位类型不能为空")));
            return;
        }
        if (positionCode == null || positionCode.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("岗位编号不能为空")));
            return;
        }
        
        try {
            int age = Integer.parseInt(ageStr);
            if (age < 18 || age > 100) {
                out.print(gson.toJson(JsonResult.error("年龄必须在18-100之间")));
                return;
            }
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date hireDate = sdf.parse(hireDateStr);
            
            BigDecimal salary = new BigDecimal(salaryStr);
            if (salary.compareTo(BigDecimal.ZERO) <= 0) {
                out.print(gson.toJson(JsonResult.error("薪资必须大于0")));
                return;
            }
            
            Employee employee = new Employee();
            employee.setId(id.trim());
            employee.setName(name.trim());
            employee.setAge(age);
            employee.setGender(gender.trim());
            employee.setPhone(phone.trim());
            employee.setHireDate(hireDate);
            employee.setPositionType(positionType.trim());
            employee.setPositionCode(positionCode.trim());
            employee.setSalary(salary);
            
            if (employeeDao.update(employee)) {
                out.print(gson.toJson(JsonResult.success("更新成功")));
            } else {
                out.print(gson.toJson(JsonResult.error("更新失败")));
            }
            
        } catch (NumberFormatException e) {
            out.print(gson.toJson(JsonResult.error("数字格式错误")));
        } catch (ParseException e) {
            out.print(gson.toJson(JsonResult.error("日期格式错误")));
        }
    }
    
    /**
     * 删除员工
     */
    private void handleDelete(HttpServletRequest request, PrintWriter out) {
        String id = request.getParameter("id");
        if (id == null || id.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("ID不能为空")));
            return;
        }
        
        if (employeeDao.delete(id)) {
            out.print(gson.toJson(JsonResult.success("删除成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("删除失败")));
        }
    }
    
    /**
     * 批量删除员工
     */
    private void handleDeleteBatch(HttpServletRequest request, PrintWriter out) {
        String idsStr = request.getParameter("ids");
        if (idsStr == null || idsStr.trim().isEmpty()) {
            out.print(gson.toJson(JsonResult.error("请选择要删除的员工")));
            return;
        }
        
        String[] ids = idsStr.split(",");
        if (employeeDao.deleteBatch(ids)) {
            out.print(gson.toJson(JsonResult.success("批量删除成功")));
        } else {
            out.print(gson.toJson(JsonResult.error("批量删除失败")));
        }
    }
}
